<template>
  <div>
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="节点ID" prop="nodeId">
            <el-input v-model="queryParams.nodeId" placeholder="请输入节点ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="宿舍楼ID" prop="buildingId">
            <el-input v-model="queryParams.buildingId" placeholder="请输入宿舍楼ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="楼层ID" prop="floorId">
            <el-input v-model="queryParams.floorId" placeholder="请输入楼层ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="宿舍ID" prop="roomId">
            <el-input v-model="queryParams.roomId" placeholder="请输入宿舍ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学生ID" prop="studentId">
            <el-input v-model="queryParams.studentId" placeholder="请输入学生ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="班级ID" prop="classId">
            <el-input v-model="queryParams.classId" placeholder="请输入班级ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="入住时间" style="width: 308px">
            <el-date-picker
                v-model="dateRangeCheckInTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item label="类型：1舍长，2舍员" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型：1舍长，2舍员" clearable>
              <el-option
                v-for="dict in sg_member_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <!-- <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete(null,'退宿')"
              v-hasPermi="['dormitory:buildingTree:remove']"
              >退宿</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Remove"
              :disabled="multiple"
              @click="handleDelete(null,'停宿')"
              v-hasPermi="['dormitory:buildingTree:stop']"
              >停宿</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Switch" :disabled="multiple" @click="showChange" v-hasPermi="['dormitory:buildingTree:change']"
              >更换宿舍</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table stripe v-loading="loading" :data="roomMemberList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生姓名" align="center" prop="studentName" width="120" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="student_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="所属班级" align="center" prop="className" width="120" />
        <el-table-column label="学号" align="center" prop="studentNo" />
        <el-table-column label="所属宿舍楼" align="center" prop="buildingName" width="120" />
        <el-table-column label="楼层" align="center" prop="floorName" />
        <el-table-column label="宿舍" align="center" prop="roomName" />
        <el-table-column label="是否舍长" align="center" prop="type" width="120">
          <template #default="scope">
            <dict-tag :options="boolean_num_status" :value="scope.row.type" />
            <!-- <span v-if="scope.row.type == 1">是</span>
            <span v-else>否</span> -->
          </template>
        </el-table-column>
        <el-table-column label="入住时间" align="center" prop="checkInTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.checkInTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="顺序" align="center" prop="orderNum" /> -->
        <el-table-column label="备注" align="center" prop="remark" />
        <!-- <el-table-column label="状态：1启用，2删除" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="use_status" :value="scope.row.status" />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)" v-hasPermi="['dormitory:roomMember:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="退宿" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row,'退宿')"
                v-hasPermi="['dormitory:roomMember:remove']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="停宿" placement="top">
              <el-button
                link
                type="primary"
                icon="Remove"
                @click="handleDelete(scope.row,'停宿')"
                v-hasPermi="['dormitory:roomMember:stop']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="更换宿舍" placement="top">
              <el-button link type="primary" icon="Switch" @click="showChange(scope.row)" v-hasPermi="['dormitory:buildingTree:change']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="740px" append-to-body>
      <el-form ref="roomMemberFormRef" :model="form" :rules="rules" label-width="100px" :inline="true" class="add-form">
        <el-form-item label="学生名称" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生" />
        </el-form-item>
        <el-form-item label="宿舍楼" prop="buildingName">
          <el-input v-model="form.buildingName" placeholder="请输入宿舍楼" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="楼层" prop="floorName">
          <el-input v-model="form.floorName" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="宿舍" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入宿舍" />
        </el-form-item>
        <el-form-item label="是否舍长" prop="type">
          <el-select v-model="form.type" placeholder="请选择是否舍长">
            <el-option v-for="dict in boolean_num_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入住时间" prop="checkInTime">
          <el-date-picker clearable v-model="form.checkInTime" type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择入住时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入顺序" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark" style="width: 95%;">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- <el-form-item label="状态：1启用，2删除" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in use_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template> -->
    </el-dialog>
    <el-dialog title="更换宿舍" v-model="changeDialog.visible" width="750px" append-to-body>
      <el-form ref="changeFormRef" :model="changeForm" :rules="rules2" label-width="110px">
        <el-form-item label="宿舍" prop="nodeId">
          <el-tree-select
            v-model="changeForm.nodeId"
            :data="buildingTreeList"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            :default-expanded-keys="['1']"
            value-key="id"
            placeholder="请选择宿舍"
            @current-change="treeChange"
            filterable
            check-strictly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitChange">确 定</el-button>
          <el-button @click="hideChange">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RoomMember" lang="ts">
import { listRoomMember, getRoomMember, delRoomMember, addRoomMember, updateRoomMember } from '@/api/dormitory/roomMember';
import { RoomMemberVO, RoomMemberQuery, RoomMemberForm } from '@/api/dormitory/roomMember/types';

const props = defineProps({
  nodeId: String || Number || undefined,
  sourceId: String || Number || undefined
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sg_member_type, use_status, boolean_num_status, student_sex } = toRefs<any>(
  proxy?.useDict('sg_member_type', 'use_status', 'boolean_num_status', 'student_sex')
);

const roomMemberList = ref<RoomMemberVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCheckInTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const roomMemberFormRef = ref<ElFormInstance>();
const isEdit = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RoomMemberForm = {
  id: undefined,
  nodeId: undefined,
  buildingId: undefined,
  floorId: undefined,
  roomId: undefined,
  studentId: undefined,
  classId: undefined,
  checkInTime: undefined,
  type: undefined,
  orderNum: undefined,
  remark: undefined,
  status: 1
};
const data = reactive<PageData<RoomMemberForm, RoomMemberQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nodeId: undefined,
    buildingId: undefined,
    floorId: undefined,
    roomId: undefined,
    studentId: undefined,
    classId: undefined,
    type: undefined,
    orderNum: undefined,
    status: 1,
    params: {
      checkInTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生ID不能为空', trigger: 'blur' }],
    classId: [{ required: true, message: '班级ID不能为空', trigger: 'blur' }],
    checkInTime: [{ required: true, message: '入住时间不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '是否舍长不能为空', trigger: 'change' }]
  }
});

const rules2 = ref({
  nodeId: [{ required: true, message: '宿舍不能为空', trigger: 'change' }]
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCheckInTime.value, 'CheckInTime');
  const res = await listRoomMember(queryParams.value);
  roomMemberList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  roomMemberFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCheckInTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

const studentIds = ref<Array<string | number>>([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: RoomMemberVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  studentIds.value = selection.map((item) => item.studentId);
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加学生';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RoomMemberVO) => {
  reset();
  // const _id = row?.id || ids.value[0];
  // const res = await getRoomMember(_id);
  // Object.assign(form.value, res.data);
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = '详情';
};

/** 提交按钮 */
const submitForm = () => {
  roomMemberFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRoomMember(form.value).finally(() => (buttonLoading.value = false));
      } else {
        form.value.nodeId = props.nodeId;
        form.value.roomId = props.sourceId;
        await addRoomMember(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RoomMemberVO, tipText: String) => {
  const _ids = row?.id || ids.value;
  let tip;
  if (!row?.id) {
    tip = `是否确认${tipText}选中的学生？`;
  } else {
    tip = `是否确认${tipText}"${row.studentName}"？`;
  }
  await proxy?.$modal.confirm(tip).finally(() => (loading.value = false));
  await delRoomMember(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'dormitory/roomMember/export',
    {
      ...queryParams.value
    },
    `roomMember_${new Date().getTime()}.xlsx`
  );
};

const loadList = (type: string, typeId: string) => {
  queryParams.value.buildingId = undefined;
  queryParams.value.floorId = undefined;
  queryParams.value.roomId = undefined;
  console.log(type, typeId);
  switch (type) {
    case 'T':
      break;
    case 'B':
      queryParams.value.buildingId = typeId;
      break;
    case 'F':
      queryParams.value.floorId = typeId;
      break;
    case 'R':
      queryParams.value.roomId = typeId;
      break;
    default:
      break;
  }
  getList();
};

const editChange = () => {
  isEdit.value = !isEdit.value;
};

import { listBuildingTree } from '@/api/dormitory/buildingTree';
const buildingTreeList = ref<BuildingTreeVO[]>([]);
const changeFormRef = ref(null);
const changeForm = ref({
  nodeId: null,
  roomId: null,
  studentIds: []
});
const changeDialog = ref({
  visible: false,
  title: ''
});
/** 查询宿舍楼管理列表 */
const getBuildingTree = async () => {
  const res = await listBuildingTree();
  const data = proxy?.handleTree<BuildingTreeVO>(res.data, 'id', 'parentId');
  console.log('data', data);
  if (data) {
    buildingTreeList.value = data;
  }
};
const treeChange = (node: any) => {
  if (node.type != 'R') {
    changeForm.value.nodeId = null;
    changeForm.value.roomId = null;
    ElMessage.warning('选择的节点类型必须为房间');
    changeFormRef?.value.clear();
    return;
  }
  changeForm.value.roomId = node?.sourceId;
};
const showChange = async (row: any) => {
  changeFormRef.value?.resetFields();
  changeForm.value = {
    nodeId: null,
    roomId: null,
    studentIds: []
  };
  if (buildingTreeList.value.length == 0) {
    await getBuildingTree();
  }
  let _ids = studentIds.value;
  if (row?.id) {
    _ids = [row.studentId];
  }
  console.log('ids', _ids);
  changeForm.value.studentIds = _ids;
  changeDialog.value.visible = true;
};

const hideChange = async () => {
  changeDialog.value.visible = false;
};

const submitChange = async () => {
  changeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addRoomMember(changeForm.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('修改成功');
      hideChange();
      await getList();
    }
  });
};

const clearParams = () => {
  queryParams.value.studentName = undefined;
};

defineExpose({
  loadList,
  clearParams
});
</script>
